package helpers;

import java.io.IOException;
import java.net.URL;

import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;
import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class GoogleStorageHelper {
	public static void getFile(String urlString, String fileName) throws IOException {
		String BUCKETNAME = "static.services79.com/ats100";
		
		byte[] img = null;
		URLFetchService fetchService =
            URLFetchServiceFactory.getURLFetchService();
		// Fetch the image at the location given by the url query string parameter
		URL url = new URL(urlString);
		// Fetch the image at the location given by the url query string parameter
		FetchOptions fetchOptions =FetchOptions.Builder.withDefaults();
		fetchOptions.setDeadline((double)30*60);
		HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, fetchOptions);
        HTTPResponse fetchResponse = fetchService.fetch(request);
        
        String fetchResponseContentType = null;
        for (HTTPHeader header : fetchResponse.getHeaders()) {
            // For each request header, check whether the name equals
            // "Content-Type"; if so, store the value of this header
            // in a member variable
            if (header.getName().equalsIgnoreCase("content-type")) {
                fetchResponseContentType = header.getValue();
                break;
            }
        }
        if (fetchResponseContentType != null) {
        	img = (byte[]) fetchResponse.getContent();
        	
        	FileService fileService = FileServiceFactory.getFileService();
		    GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
		       .setBucket(BUCKETNAME)
		       .setKey(fileName)
		       .setMimeType(fetchResponseContentType)
		       .setAcl("public_read").setCacheControl("public, max-age=6000");
		       
		    
		    AppEngineFile writableFile =
		        fileService.createNewGSFile(optionsBuilder.build());
		    // Open a channel to write to it
		    boolean lock = true;
		    FileWriteChannel writeChannel =
		        fileService.openWriteChannel(writableFile, lock);
		 
		    // This time we write to the channel using standard Java
		    writeChannel.write(java.nio.ByteBuffer.wrap(img));
		    // Now finalize
		    writeChannel.closeFinally();
		    System.out.println("Done writing...");
		    
        }
	}
}
